package cn._51doit.flink.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCount2 {

    public static void main(String[] args) throws Exception {

        //1.创建Flink执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //2.调用Source创建DataStream
        DataStreamSource<String> lines = env.socketTextStream(args[0], Integer.parseInt(args[1]));
        //3.调用Transformation(s)
        //切分压平，并且将单词和1组合
//        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
//            @Override
//            public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
//                String[] words = line.split(" ");
//                for (String word : words) {
//                    collector.collect(Tuple2.of(word, 1)); //将数据输出给下一个算子使用
//                }
//            }
//        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndOne = lines.flatMap(new LineSplitor());

        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndOne.keyBy(0).sum(1);

        //4.调用Sink
        summed.print();

        //5.启动
        env.execute();

    }


    private static class LineSplitor implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String line, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = line.split(" ");
            for (String word : words) {
                //输出数据
                collector.collect(Tuple2.of(word, 1));
            }
        }
    }
}
